package com.sduept.nwld.mobile.manager;

import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.core.dao.SuperDAO;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FaultMobileManager {
	private static final long FAULT_TIME_INTERVER=60000;
	@Autowired
	private SuperDAO dao;
	
	/**
	 * 获取双端故障录播文件信息,如果找到双端返回2条数据,如果找不到返回长度为0的二维数组
	 * @param deviceId
	 * @param faultTime
	 * @return [[faultFileId,录波器Id,录波器名称,stationId,stationName]]
	 */
	public String[][] findFaultFileId(String deviceId,Date faultTime){
		String [][] rtn = new String[0][0];
		DateTime s = new DateTime(faultTime.getTime());
		DateTime startTime = s.minus(FAULT_TIME_INTERVER);
		DateTime endTime = s.plus(FAULT_TIME_INTERVER);
		String sql = "select t.fault_file_id,t.fault_device_id,t2.name,t2.sub_id,t2.sub_name " +
				" from t_lbtz_fault_report t " +
				" left join t_cim_waverecord_equipment t2 on t.fault_device_id=t2.id " +
				" where  t.device_id = ? and t.fault_time > ? and t.fault_time < ? order by t.fault_time";
		Object[] whereArgs = new Object[3];
		whereArgs[0] = deviceId;
		whereArgs[1] = startTime.toString("yyyy-MM-dd HH:mm:ss");
		whereArgs[2] = endTime.toString("yyyy-MM-dd HH:mm:ss");
		List<?> obs = dao.nativeQuery(sql, whereArgs);
		int len = obs.size();
		Map<String,Object[]> files = new HashMap<>();
		
		if(len > 0){
			for(Object o : obs){
				Object[] os = (Object[])o;
				if(os[1] != null){
					Object[] existOs = files.get(os[1].toString());
					if(existOs == null){
						files.put(os[1].toString(), os);
					}
				}
			}
			len = files.size();
			rtn = new String[len][5];
			int i = 0;
			for(Object[] os : files.values()){
				for (int j = 0; j < os.length; j++) {
					if(os[j] != null)
						rtn[i][j] =  os[j].toString(); 
				}
				i++;
			}
		}
		return rtn;
	}
	
	public FaultRecord getFaultRecordById(String id){
		return dao.findById(id, FaultRecord.class);
	}
	
}
